package atomic.atomicinteger;

import lombok.Data;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author ZhuQi
 * @ClassName Demo
 * @Date 2022/9/16 10:16
 * @Version 1.0
 * @Description 测试 atomic Integer
 *   需求，完成50个线程的 i++ 操作
 */
@Slf4j
public class Demo {

    static int threadCount = 50;

    @SneakyThrows
    public static void main(String[] args) {
        Resources resources = new Resources();
        CountDownLatch countDownLatch = new CountDownLatch(threadCount);

        for (int i = 0; i < threadCount; i++) {
            new Thread(()->{
                for (int j = 0; j < 1000; j++) {
                    resources.addPlusPlus();
                }
                countDownLatch.countDown();
            }).start();
        }
        countDownLatch.await();
        log.info("资源类的值为：{}", resources.getAtomicInteger().get());
    }
}

@Data
class Resources{
    private AtomicInteger atomicInteger = new AtomicInteger();

    public void addPlusPlus(){
        atomicInteger.incrementAndGet();
    }
}